# -*- coding: utf-8 -*-


from __future__ import print_function, absolute_import, unicode_literals
import numpy as np
import pandas as pd
from gm.api import *
import talib


def init(context):
    context.symbol = 'DCE.Y'
    # context.symbol = 'CZCE.FG'  #
    # 订阅SHFE.rb1801, bar频率为1min
    subscribe(symbols=context.symbol, frequency='60s')
    # 获取过去300个价格数据
    timeseries = history_n(symbol=context.symbol, frequency='60s', count=300, fields='close', fill_missing='Last',
                           end_time='2017-07-01 08:00:00', df=True)['close'].values
    print('timeseries', timeseries)
    context.timeseries = timeseries
    # 获取网格区间分界线


def on_bar(context, bars):
    # bar = bars[0]

    ma_240 = talib.MA(context.timeseries, timeperiod=240)
    ma_62 = talib.MA(context.timeseries, timeperiod=62)
    ma_5 = talib.MA(context.timeseries, timeperiod=5)
    # print('ma_240', ma_240)
    upper, middle, lower = talib.BBANDS(context.timeseries, timeperiod=15, nbdevup=1, nbdevdn=1, matype=0)

    upper = upper[-1]
    lower = lower[-1]

    print('布林线', upper, lower)

    # if prices < lower and curPosition == 0 and change > 0.97:
    #     # 价格低于下限时买入
    #     order_target_percent(context.s1, 1)
    #
    # elif (prices > upper and curPosition != 0) or change < 0.97:
    #     # 价格高于上限时卖出
    #     order_target_percent(context.s1, 0)

    if ma_240[-1] < ma_62[-1] < ma_5[-1]:
        order_target_percent(symbol=context.symbol, percent=0.5, order_type=OrderType_Market,
                             position_side=PositionSide_Long)
        # print('空', '差值：', ma_5[-1] - ma_240[-1])
    elif ma_240[-1] > ma_62[-1] > ma_5[-1]:
        order_target_percent(symbol=context.symbol, percent=0.5, order_type=OrderType_Market,
                             position_side=PositionSide_Long)
        # print('多', '差值：', ma_5[-1], ma_62[-1], ma_240[-1])


if __name__ == '__main__':
    run(strategy_id='5edce944-9e20-11e9-a24c-b499baf0193a',
        filename='布林线.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2018-07-01 08:00:00',
        backtest_end_time='2019-07-01 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0015,
        backtest_slippage_ratio=0.0001)
